import { ref, shallowRef } from 'vue'

import { catchFn } from '@/libs/common'
import { getResultList, deleteResult } from './api'
import { topMessage } from '@/components/TopMessage/data'
import { setSessionId as setSessionId_anxiety } from '../../anxiety/detail/data'

/** 测试列表 */
const list = shallowRef<T_ResultItem[]>([])
/** 当前选择 */
const curIdx = ref(-1)
/** 当前页码 */
let page = 0
const isBottom = ref(false)
const isUpdating = ref(false)

export { list, curIdx, isBottom, isUpdating }

/**
 * 更新测试结果
 */
const update = async () => {
  if (isUpdating.value || isBottom.value) return
  else isUpdating.value = true

  await catchFn(async () => {
    const { data } = await getResultList(++page, 10)

    list.value = [...list.value, ...data.list]
    isBottom.value = !data.hasNext
  })

  isUpdating.value = false
}

/**
 * 查看报告
 * @param item 报告数据
 */
const viewReport = (item: T_ResultItem) => {
  switch (item.typeCode) {
    case 'anxiety':
      setSessionId_anxiety(item.sessionId)
      uni.navigateTo({ url: '/pages/quiz/anxiety/detail/index' })

      break

    case 'fortune':
      uni.navigateTo({
        url: `/pages/community/friend/report/info?type=${item.type}&friendId=${item.friendId}`,
      })

      break

    case 'mbti_28':
    case 'mbti_93':
    case 'mbti_200':
      setSessionId_anxiety(item.sessionId)
      uni.navigateTo({
        url: `/pages/quiz/mbti/result/index?typeCode=${item.typeCode}&sessionId=${item.sessionId}`,
      })

      break

    default:
      topMessage.dev()
  }
}

/**
 * 删除报告
 */
const deleteReport = async () => {
  const item = list.value[curIdx.value]

  if (!item) {
    topMessage.warn('请选择报告或测试')
    return
  }

  // 删除确认
  const confirm = await new Promise(resolve => {
    uni.showModal({
      title: '提示',
      content: `确认删除“${item.reportName}”吗`,
      success: res => resolve(res.confirm),
    })
  })

  if (!confirm) return

  catchFn(async () => {
    await deleteResult(item.id, item.typeCode)

    const { data } = await getResultList(page, 10)

    list.value = [...list.value.slice(0, (page - 1) * 10), ...data.list]
    isBottom.value = !data.hasNext
    curIdx.value = -1

    topMessage.success('删除成功')
  })
}

/**
 * 还原状态
 */
const clear = () => {
  list.value = []
  curIdx.value = -1
  isBottom.value = false
  isUpdating.value = false
  page = 0
}

export { update, viewReport, deleteReport, clear }
